import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import type { Router } from 'vue-router'
import router from '@/router'
import { authApi } from '@/api/user/auth'
import { ElMessage } from 'element-plus'

export const useLogin = () => {
  const username = ref('')
  const password = ref('')
  const userStore = useUserStore()
  const loading = ref(false)

  const handleLogin = async () => {
    if (loading.value) return
    loading.value = true

    try {
      const response = await authApi.login({
        username: username.value,
        password: password.value
      })
      
      if (response.data.code === 200) {
        userStore.setUserInfo(response.data.data)
        ElMessage.success('登录成功')
        router.push('/')
      } else {
        ElMessage.error(response.data.message || '登录失败')
      }
    } catch (error: any) {
      if (error.response) {
        ElMessage.error(error.response.data.message || '登录失败')
      } else {
        ElMessage.error('网络错误，请稍后重试')
      }
      console.error('登录失败:', error)
    } finally {
      loading.value = false
    }
  }

  return {
    username,
    password,
    loading,
    handleLogin
  }
} 